<!doctype html>

<html>
 
<!--	
	<script
		src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></script>
	<script
		src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
	-->
	
	<script
		src="jquery-1.4.2.min.js" ></script>
	<script
		src="jquery-ui-1.7.2.custom.min.js"></script>

	<script src="nodeMap.js"></script>
	<style>
#console{position:fixed; top:0; right:0; z-index:100; background:black;
	color:white; width:400px}
#console p#out{display:none; }
#board{position:relative; width:300px; height:300px; background:#DDDDDD;
	z-index:10 }
.pion{position:absolute; top:10px; left:10px;display: block;width:50px; height:50px; background:#777  }
#joueur{background:blue;z-index:50}
.others{background:red; position:relative;z-index:1}
	</style>
	<body>
		<h1>Test NODE MAP</h1>
		<div id="console">
			<p>Position : X : <span id="x"></span>| Y : <span id="y"/>i</span></p>
			<h2 id="outTitle">Console (click to hide/show)</h2><p id="out"></p>
		</div>
		<!--
		No way right now to do something simple >> going for an easier way using
		html and jQuery
		<svg dth="600px" height="600px">
			<circle cx="150px" cy="100px" r="30px" fill="#ff0000" stroke="#000000" stroke-width="5px" id="piece"/>
			</svg>-->
		<div id="board">
		</div>
	</body>
	<script>
		//	startSocket();	
		
		$(document).ready(function(){
			if(window["WebSocket"]){
				var ws = new WebSocket("ws://localhost:8020/service");
				var oppIDs = {};
				ws.onopen = function() {
					$("#board").append("<div id='joueur' class='pion'>You</pion>");
					/*setInterval(function(){
						ws.send("[0,0]");
					}, 100);*/
					var newPos=[];
					var lastPos=newPos;

					var updatePosition=function(){
						var position = $("#joueur").position();
						$("#x").html(position.left);
						$("#y").html(Math.floor(position.top));
						newPos=[position.left,Math.floor(position.top)];
					};

					setInterval(function(){
						if(lastPos[0]!=newPos[0] || lastPos[1]!=newPos[1]){
							lastPos=newPos;
							ws.send("["+newPos.toString()+"]");
						}
					}, 10);

					$(".pion").draggable({ containment: 'parent',
						cursorAt: { cursor: 'crosshair', top:0, left:0 } ,
						drag:function(e,ui){
							updatePosition();
						}
					});

					updatePosition()
				};
				ws.onmessage = function (evt) {
					$("p#out").prepend(evt.data+"<br/>");
					if(evt.data=="ping"){
						ws.send("pong");
					}
					else{
						var oppData = jQuery.parseJSON(evt.data);
						var idOpp = oppData[0];
						var posOpp = oppData[1];
						if(!oppIDs[idOpp]){
							oppIDs[idOpp] = posOpp;
							$("#board").append("<div id='opp"+idOpp+"' class='pion others'>"+idOpp+"</div>");
						}
						$("#opp"+idOpp).css("left",posOpp[0]).css("top",posOpp[1]);
					}
				};
			}
			else{
				alert("Nope nope nope websocket nope nope nope");
			}
			
			$("#outTitle").click(function(){$("#out").toggle();});
			//$("#piece").ready(function(){alert(this);});
		});	
	</script>
</html>
